import type { RequestUrlParam } from 'obsidian'
import { request } from 'obsidian'
import type { GiteeParms } from '../parms/parms-gitee'
import { getBase64, getRandomFileName } from '../utils/file-helper'
import { EmoUploader } from '../base/emo-uploader'

export class GiteeUploader extends EmoUploader {
  parms!: GiteeParms
  constructor(giteeParms: GiteeParms) {
    super()
    this.parms = giteeParms
  }

  async upload(file: File): Promise<string> {
    let filePath = this.parms.path + (this.parms.random ? getRandomFileName() : file.name)
    const content = await getBase64(file)

    const req: RequestUrlParam = {
      url: `https://gitee.com/api/v5/repos/${this.parms.required.owner}/${this.parms.required.repo}/contents/${encodeURIComponent(filePath)}`,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        access_token: this.parms.required.access_token,
        branch: this.parms.required.branch,
        content,
        message: this.parms.required.message
      })
    }

    const response = await request(req)
    const jsonResp = JSON.parse(response)
    if (jsonResp.content) {
      return `![gitee](${jsonResp.content.download_url})`
    }
    throw new Error(`Gitee upload failed: ${jsonResp.message} (owner: ${this.parms.required.owner}, repo: ${this.parms.required.repo})`)
  }
}